<?php
/**
 * @link https://www.len168.com
 * @copyright Copyright (c) 2020/9/15 len168.com
 * @author toshcn <toshcn@foxmail.com>
 */

namespace common\components\oss;

use Yii;

/**
 * 本地 上传组件
 * @package common\components\oss
 */
class LocalOss extends DefaultOss implements OssInterface
{
    /** @var string 本地访问域名 */
    private $_host = '';

    private $_basePath = '';

    public function init()
    {
        parent::init();
        $this->_basePath = Yii::getAlias('@upload/');
    }

    /**
     * 配置组件
     * @param array $config 配置数组
     */
    public function setConfig($config)
    {
        if (is_array($config)) {
            $this->_host = isset($config['host']) && !empty($config['host']) ? trim($config['host'], '/') . '/' : '';
        }
    }

    /**
     * 生成文件路径
     * @param $uid integer 上传用户ID
     * @return mixed
     */
    public function generateFilePath($uid = 0)
    {
        return substr(md5($uid), 0, 6) . '/local/' . date('Y-m-d') . '/' . $uid . '/';
    }

    /**
     * 生成头像文件路径
     * @param $uid integer 上传用户ID
     * @return mixed
     */
    public function generateAvatarFilePath($uid = 0)
    {
        return substr(md5($uid), 0, 6) . '/avatar_local/' . date('Y-m-d') . '/' . $uid . '/';
    }

    /**
     * 保存文件到服务器
     * @param string $object OSS保存的文件对象名称
     * @param object $file 要上传的本地文件对象
     * @param bool $deleteTempFile 是否删除临时文件.
     * @see \yii\web\UploadedFile::getInstanceByName()
     * @return mixed
     */
    public function upload($object, &$file, $deleteTempFile = true)
    {
        try {
            // 上传
            @mkdir(dirname($this->_basePath . $object), 0755, true);
            if ($file->saveAs($this->_basePath . $object, $deleteTempFile)) {
                return [
                    'code' => 1,
                    'message' => '上传本地成功',
                    'data' => [
                        'path' => $this->_host ? $this->_host . $object : $object,
                        'handler' => 'localOss'
                    ]
                ];
            }
            return ['code' => 0, 'message' => '上传本地服务器失败'];
        } catch (\Exception $e) {
            return ['code' => 0, 'message' => $e->getMessage()];
        }
    }

    /**
     * 删除文件
     * @param string $object 要删除的OSS对象文件路径
     * @return mixed
     */
    public function delete($object)
    {
        try {
            if ($this->_host) {
                $object = str_replace($this->_host, '', $object);
            }
            @unlink($this->_basePath . $object);
            return ['code' => 1, 'message' => '删除本地文件成功', 'data' => []];
        } catch (\Exception $e) {
            return ['code' => 0, 'message' => $e->getMessage()];
        }
    }
}
